//
//  ViewController.m
//  FengWoFilterTickerDemo
//
//  Created by YingShi on 15/10/26.
//  Copyright © 2015年 FengWo. All rights reserved.
//

#import "ViewController.h"
#import "CTAssetsPickerController.h"
#import "ActionViewController.h"
#import <Photos/Photos.h>

@interface ViewController () <UIImagePickerControllerDelegate,CTAssetsPickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIGestureRecognizerDelegate>
{
    IBOutlet UIImageView *imgChosen;
    IBOutlet UIView      *viewWindow;
    
    CGFloat lastScale;
}

@property (nonatomic, strong) UIImagePickerController *picker;
//@property (nonatomic, strong) NSMutableArray *imageArray; // 牌友圈已经发布出去的照片 -- 测试专用数组
@property (nonatomic, strong) NSMutableArray *assetsArray; // 存放从手机相册中选取的照片

@end

#define iOS8 ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0 ? YES : NO)
#define iOS9 ([[UIDevice currentDevice].systemVersion doubleValue] >= 9.0 ? YES : NO)

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 画边框
    viewWindow.layer.borderColor = [UIColor whiteColor].CGColor;
    viewWindow.layer.borderWidth = 1;
    viewWindow.userInteractionEnabled = YES;
    
    // 添加缩放手势
    UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchImage:)];
    [pinchRecognizer setDelegate:self];
    [viewWindow addGestureRecognizer:pinchRecognizer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)pinchImage:(UIGestureRecognizer *)gesture
{
//    //当手指离开屏幕时,将lastscale设置为1.0
//    if([(UIPinchGestureRecognizer*)senderstate] == UIGestureRecognizerStateEnded) {
//        lastScale = 1.0;
//        return;
//    }
    
    CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer *)gesture scale]);
    CGAffineTransform currentTransform = imgChosen.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    [imgChosen setTransform:newTransform];
    lastScale = [(UIPinchGestureRecognizer*)gesture scale];
}

- (IBAction)btnAddPhotoClicked:(id)sender
{
    
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.delegate = self;
    self.picker.allowsEditing = YES;
    
    if (iOS8) {
        UIAlertController *alertUC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        __weak typeof(self) weakSelf = self;
        UIAlertAction *camaraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf selectImageFromTakePhoto];
            
        }];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 相册多选
            if (!weakSelf.assetsArray) {
                weakSelf.assetsArray = [[NSMutableArray alloc] init];
            }
            else {
                [weakSelf.assetsArray removeAllObjects];
            }
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            // 单选。
            picker.maximumNumberOfSelection = 1;
            picker.delegate = weakSelf;
            [weakSelf presentViewController:picker animated:YES completion:nil];
            
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertUC addAction:camaraAction];
        [alertUC addAction:photoAction];
        [alertUC addAction:cancelAction];
        [self presentViewController:alertUC animated:YES completion:nil];
        
    }
    else {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从手机相册选择",  nil];
        [sheet showInView:self.view];
    }

}

- (IBAction)btnNextClicked:(id)sender
{
    if (!imgChosen.image) {
        return;
    }else
    {
        [self performSegueWithIdentifier:@"goToActionVC" sender:self];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    ActionViewController *aVC = segue.destinationViewController;
    
    // 首先拷贝屏幕
    UIImage *imgScreen = [self convertScreenToImage];
    // 然后按照取景框裁剪，注意屏幕的scale
    CGFloat theScale = [UIScreen mainScreen].scale;
    UIImage *img = [self getImageFromImage:imgScreen subImageSize:CGSizeMake(viewWindow.bounds.size.width, viewWindow.bounds.size.height) subImageRect:CGRectMake(viewWindow.frame.origin.x * theScale, viewWindow.frame.origin.y * theScale, viewWindow.bounds.size.width * theScale, viewWindow.bounds.size.height * theScale)];
    
    aVC.imgInput = img;
}

// 拍照后的照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [imgChosen setImage:image];
    
}

// 选择相册里的照片
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    for (int i = 0; i < assets.count; i++) {
        
        NSLog(@"image is %@", assets[i]);
        
        if (1/*!iOS8*/) {
            // 按理是小于iOS8的系统，由于else代码尚未debug完毕，暂定用9.0已经淘汰的ALAsset。
            ALAsset *als = assets[i];
            
            ALAssetRepresentation *alsR = [als defaultRepresentation];
            
            
            UIImage *image = [UIImage imageWithCGImage:[alsR fullResolutionImage] scale:[alsR scale] orientation:[alsR orientation]];
            [imgChosen setImage:image];
            
        }else
        {
            // 仍然需要debug
            PHAsset *phs = assets[i];
            // Prepare the options to pass when fetching the live photo.
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
            options.networkAccessAllowed = NO;
            options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
                /*
                 Progress callbacks may not be on the main thread. Since we're updating
                 the UI, dispatch to the main queue.
                 */
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    self.progressView.progress = progress;
//                });
            };
            
            [[PHImageManager defaultManager] requestImageForAsset:phs targetSize:imgChosen.frame.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
                // Hide the progress view now the request has completed.
//                self.progressView.hidden = YES;
                
                // Check if the request was successful.
                if (!result) {
                    return;
                }
                
                // Show the UIImageView and use it to display the requested image.
                //[self showStaticPhotoView];
                imgChosen.image = result;
            }];
        }
    }
    
    // 下一步
    
}
// 取消选择。
- (void)assetsPickerControllerDidCancel:(CTAssetsPickerController *)picker
{
    
}

/**
 *   拍照
 */
- (void)selectImageFromTakePhoto
{
    if([self isAvailabletakePhoto] == YES)
    {
        self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.picker animated:YES completion:nil];
    }
}

/**
 *   是否支持拍照
 *
 *  @return YES 是支持  NO是不支持
 */
- (BOOL)isAvailabletakePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]) {
        return YES;
    }
    return NO;
}

// 拷贝屏幕
-(UIImage *)convertScreenToImage
{
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了

    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, YES, [UIScreen
                             mainScreen].scale);
    
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}

// 图片裁剪
-(UIImage *)getImageFromImage:(UIImage *)superImage subImageSize:(CGSize)subImageSize subImageRect:(CGRect)subImageRect {

    CGImageRef imageRef = superImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, subImageRect);
    UIGraphicsBeginImageContext(subImageSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, subImageRect, subImageRef);
    UIImage* returnImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext(); //返回裁剪的部分图像
    return returnImage;
}

@end
